package com.trytech.mongoocrawler.server;

import com.trytech.mongoocrawler.server.common.enums.LifeCycle;
import com.trytech.mongoocrawler.server.common.queue.DisruptorContext;
import com.trytech.mongoocrawler.server.transport.*;
import com.trytech.mongoocrawler.server.transport.http.CrawlerHttpRequest;
import com.trytech.mongoocrawler.server.xml.CrawlerXmlConfigBean;
import org.apache.commons.lang3.StringUtils;

import java.util.UUID;

/**
 * 一次爬取会话
 * 会话的生命周期包括：
 *      INITIALIZED=0-初始化
 *      RUNNING=1-已运行
 *      PAUSED=2-暂停
 *      DESTORYED=3-已销毁
 */
public abstract class CrawlerSession {
    //工作线程池
    protected final static TaskThreadPool threadPool = new TaskThreadPool();
    //会话ID
    protected String sessionId;
    //crawler的配置
    protected CrawlerXmlConfigBean sessionConfig;
    //Disruptor上下文
    protected DisruptorContext disruptorContext;
    //url内存队列
    protected UrlManager urlManager = new LocalUrlManager();
    //会话ID生成器
    protected LocalCrawlerSession.SessionIdGenerator generator = new LocalCrawlerSession.SessionIdGenerator();
    //生命周期
    protected LifeCycle lifeCycle;

    public abstract boolean isPaused();
    public abstract boolean isDestoryed();

    public DisruptorContext getDisruptorContext() {
        return disruptorContext;
    }

    public void submitTask(CrawlerHttpRequest request) {
        threadPool.submit(new TaskWorker(request, this));
    }

    public CrawlerXmlConfigBean getSessionConfig() {
        return this.sessionConfig;
    }

    public void pushUrl(UrlParserPair urlParserPair) {
        urlManager.pushUrl(urlParserPair);
    }

    public String getSessionId() {
        return generator.generate();
    }

    public LifeCycle getLifeCycle() {
        return lifeCycle;
    }

    public void setLifeCycle(LifeCycle lifeCycle) {
        this.lifeCycle = lifeCycle;
    }

    protected class SessionIdGenerator {
        public String generate() {
            if (StringUtils.isEmpty(sessionId)) {
                sessionId = UUID.randomUUID().toString();
            }
            return sessionId;
        }
    }
}
